// const ROOTURL = 'https://xhwapplet.eeaassyy.com/';
// const APIURL = 'https://union.eeaassyy.com/uinterface.php';
  const APIURL = 'https://ng.cometoy.com/uinterface.php';    //王哥
//const APIURL = 'https://union.eeaassyy.com/uinterface.php';    //张轩

const g={
  version:"1.1.0",
  ttt:true, //true 开启调试  false 关闭调试
//

  ngid:1 , // 拿谷店铺id=1
  //读取商铺信息  先不用
  st:function(){
    return wx.getStorageSync('st');
  },
  //收集 formId
  formId:function( formId ){
    console.log( "formId:", formId );
  },



//-----------------------------------
  test:function(t=''){
    console.log( 'g.test:' ,t );
  },
  



//-----------------------------------
  p: function (...args){
    console.log(...args);
  },

  app: getApp(),

  /**
   * 封装 wx.requst() 为ajax
   */
  ajax: function (opt) {

    var def = {
      url: '',
      data: {},
      method: 'POST', //（需大写）有效值：OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      dataType: 'json', //
      header: {
        //'Content-type': 'application/json' , // 默认值, 
        'Content-Type': 'application/x-www-form-urlencoded'  //POST
      },
      
      //收到开发者服务成功返回的回调函数
      success: function (res) {
        console.log('ajax.success: ', res.data,res);
        
      },
      //接口调用失败的回调函数
      fail: function (res) {
        console.log('ajax.fail: ', res);
      },
      //接口调用结束的回调函数（调用成功、失败都会执行）
      complete: function (res) {
        //console.log('ajax.complete: ', res);
        wx.hideNavigationBarLoading();//隐藏导航条加载动画。
      }

    }
    var o = Object.assign({}, def, opt);//合并参数

    o.url = (o.url) ? o.url : APIURL; //处理默认 apiurl

    // if (o.url.indexOf('https') != 0  &&  o.url.indexOf('http') != 0) {
    //   o.url = ROOTURL + o.url;
    // }

    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画。
    wx.request(o);
  },

//------------------------------------------------------
  /**
   * api 数据接口
   */
  api:function(opt,isLoading = false ){

    var user = g.getUser();
    var def = {
      url: '',
      data: {
        uid: user.id,        //用户id
        ticket: user.ticket, //用户票据
      },
      method: 'POST', 
      dataType: 'json', //
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'  //POST
      },
      //收到开发者服务成功返回的回调函数
      success: function (res) {
        g.ttt && console.log('ajax.success: ',res);
        var d = res.data;
        //如果票据错误  重新登录
        if(6 == d.status){
          console.log('票据错误  重新登录');
          wx.reLaunch({
            url: '/pages/welcome/index?rebackurl=' + g.curUrl(),
          });
        }


        typeof opt.success == "function" && opt.success(res.data);

      },
      //接口调用失败的回调函数
      fail: function (res) {
        g.ttt && console.log('ajax.fail: ', res);
        typeof opt.fail == "function" && opt.fail(res);
      },
      //接口调用结束的回调函数（调用成功、失败都会执行）
      complete: function (res) {
        //g.ttt && console.log('ajax.complete: ', res);

        wx.hideNavigationBarLoading();//隐藏导航条加载动画。
        if (isLoading) { wx.hideLoading()}

        typeof opt.complete == "function" && opt.complete(res);
      }
    }
    //合并参数
    var o = Object.assign({}, def);
    //处理默认 apiurl
    o.url = (o.url) ? o.url : APIURL;

    o.data = Object.assign({}, o.data , opt.data );

    if (isLoading) {
      wx.showLoading({
        title: '加载中',
        mask:true
      })
    }

    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画。
    wx.request(o);
  },
//----------------------------------------------------------
  wxlogin: function (cb) {
    //调用微信登录接口  
    wx.login({
      success: function (loginCode) {
        g.ajax({
          data: {
            code:"20011",
            js_code: loginCode.code,
          },
          success: function (res) {
            wx.setStorageSync("user",res.data.data.info);
            var user = wx.getStorageSync('user');
            typeof cb == "function" && cb(user);
          }
        });

      }
    })
  },
//-----------------------
  islogin:function(){
    var user = g.getUser();
    if (user){
      console.log("已经登录！！！");
    }else{
     
      g.rebackurl( g.curUrl() );
      wx.reLaunch({
        url: "/pages/welcome/index",
      })
    };
  },
//----------------------
  //读取用户数据
  getUser:function(reload=false){
    if (reload){
      
    }else{
      
    }
    var user = wx.getStorageSync('user');
    return user;
  },
//-----------------
  //当前页面url
  //https://segmentfault.com/q/1010000008005954/a-1020000008187652
  curUrl: function ( WithArgs=true ){
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options    //如果要获取url中所带的参数可以查看options

    if (!WithArgs) { return url; }

    //拼接url的参数
    var urlWithArgs = url + '?'
    for (var key in options) {
      var value = options[key]
      urlWithArgs += key + '=' + value + '&'
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

    return urlWithArgs

    
  },
//-------------------------------------------------------------------------------
  alert:function(t='默认',cb=null){
    wx.showModal({
      //title: ''+t,
      content: ''+t,
      showCancel:false,
      confirmText:"知道了",
      success: function (res) {
        if (res.confirm) {
          typeof cb == "function" && cb();
        }
      }
    })
  },
  tip:function(title){
    var def = {
      icon:"none",
      title: title
    }
    wx.showToast(def);
    
  },
  tip_success:function(t){
    wx.showToast(t);
  },


//-----------------------------
/**
 * 
 */
  rebackurl:function(url=null){
    if( url ){
      wx.setStorageSync('rebackurl', url);
    }else{
      url = wx.getStorageSync('rebackurl');
    }
    return url;
  },
//-------------------------
  c2d: function (c) {
    var cent = parseInt(c % 100);
    if (cent < 10) cent = '0' + cent;
    var dol = parseInt(c / 100);
    return dol + '.' + cent;
  },

  d2c: function (d) {
    return parseInt(d * 100);
  },
//-------------------------------
  /**
   * 获取 当前地址位置
   */
  getLocation: function (cb = null) {

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        wx.setStorageSync('getLocation', res);
        // https://developers.weixin.qq.com/miniprogram/dev/api/location.html#wxgetlocationobject
        typeof cb == "function" && cb(res);
      }, fail: function (res) {
        console.log('读取地理位置错误');
      }
    });
    return wx.getStorageSync('getLocation');
  }
  
   
}







//----------------------------------------------------
// page.data.order to api son_sorder
g.son_order = function(order){
  var son_order=[];
  var order={
    go_id:  order.goods_id,
    tmoney: order.price * order.num , 
    money:  order.price * order.num , 
    amount: order.num, 
    st_id: order.st_id,
  }
  var order_str = JSON.stringify(order);
  var str = "[" + order_str +"]";
  return str;

  //son_order.push( order ); // push()尾部插入    unshift() 头部插入

  return son_order;
};

















//购物车对象
g.cart = {
  list:function(){
    var list = wx.getStorageSync('cartlist') || [];
    !(list instanceof Array) && (list = []);
    return list;
  },
  //加入购物车
  add:function(order,succ=null,fail=null){

    if ( order.num < 1 ) { g.alert('购买数量小于1');return false;}
    if (order.num > order.stock) { g.alert('购买数量超过库存（' + order.stock +'）'); return false; }

    var list = g.cart.list();

    list = this.add_step1( list , order );

    

    //list.push(order);



return false;
    wx.setStorageSync('cartlist', list);
    // g.alert('已经购物车',function(){
    //   typeof succ == "function" && succ();
    // });
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      duration: 2000,
      success:function(){
        typeof succ == "function" && succ();
      }
    })


    return true;
  },
  add_step1:function(list, order){
    console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
    console.log(list, order);
    console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');

    for(var i=0 , len = list.length ; i<len; i++){

      break;
    }
    //如果i=len说明list中没有找到   创建 商铺结构
    if(i == len ){
      var shop  = Object.assign({}, order);


      console.log(st);
    }







  },
  //数量-------------------------------------------------------------
  num: function(){
    return this.list().length;
  },
  //设置-------------------------------------------------------------
  setTabBarCartNum:function(){
    var num = this.num();
    wx.setTabBarBadge({
      index: 1,
      text: num.toString()
    })
    num || wx.removeTabBarBadge({ index: 1 })
  },
  //清空----------------------------------------------------------
  clear:function(){
    wx.setStorageSync('cartlist', []);
  }
}


module.exports = g;
